<!doctype html>
<html>
<head>
<script type="text/javascript" src="lib/blockad.js"></script>
<meta charset="utf-8">
<meta name = "format-detection" content = "telephone=no">
<meta name="viewport" content="width=320, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title></title>
<style type="text/css">
*{
	font-family: "Heiti SC","Hiragino Sans GB";
}
body{
	background-color:#FFF;
	font-size:12px;
}
.header{
	margin-bottom:10px;
}
.header>div{
	display:inline-block;
	vertical-align:top;
}
.preview{
	width: 100px;
	height: 100px;
	font-size: 0;
	text-align: center;
	line-height: 100px;
}
.preview img{
	max-width:100%;
	max-height:100%;
}
#price{
	font-size:14px;
}
.selected_opt_tag{
	line-height:20px;
}
.opt_div{
	display:inline-block;
	margin:5px 4px;
	border:1px solid #DDD;
	line-height:8px;
	color:#333;
}
.opt_div img{
	height:60px;
	width:60px;
	line-height:12px;
}
.opt_div div{
	min-width:41px;
	height:30px;
	padding: 0 10px;
	text-align: center;
    vertical-align: middle;
    line-height: 30px;
}
.opt_content_div{
	margin-bottom:10px;
}

#title{
	font-size: 14px;
}
#count{
	border-top: 1px dashed #DDD;
    height: 60px;
    padding-top:10px;
}
#count>div{
	display:table-cell;
	vertical-align:middle;
}
#name{
	padding-right:10px;
}
#controls>div{
	display:table-cell;
	vertical-align: middle;
}
#input>input{
	width: 90px;
	height: 30px;
	box-sizing: border-box;
    vertical-align: middle;
    border: 1px solid #DDD;
    border-radius: 0;
	font-size: 18px;
	text-align: center;
	padding: 0;
	-webkit-appearance: none;
}



#input{
	margin:10px 5px;
}
#minus,#plus{
	width: 30px;
	height: 30px;
	margin:10px;
    border: 1px solid #DDD;
    position: relative;
    box-sizing: border-box;
}
.c1,.c2{
	background-color:#999;
	position:absolute;
}
.c1{
	width:20px;
	height:4px;
	top:12px;
	left:4px;
}
.c2{
	width:4px;
	height:20px;
	top:4px;
	left:12px;
}
.blank,#submit{
	height: 40px;
    width: 100%;
}
#submit{
    position: fixed;
    line-height: 37px;
    bottom: 0px;
    text-align: center;
	left:0;
	z-index:9;
}
.submit-btn{
	box-shadow: 0px 0 10px rgba(0,0,0,0.4);
}
#submit>div{
	line-height: 40px;
    height: 40px;
    width: 100%;
    vertical-align: middle;
    display: inline-block;
    background-color: #B2793D;
    color: #FFF;
    font-size: 20px;
}
.forbid{
	opacity:0.3;
	cursor:not-allowed;
}
.selected{
	color:#FFF;
	background-color:black;
	border-color:black;
}
.now_price{
	color:#B2793D;
}
.result{
	width:100px;
	height:auto;
	margin:50px auto;
	font-size:18px;
	color:#888;
}
.result img{
	width:100px;
	opacity:0.4;
}
.result div{
	text-align:center;
}
.warning{
	display: none;
	margin: auto;
    background-color: rgba(255,0,0,0.1);
    padding: 10px;
    color: #F00;
    font-size: 15px;
    margin-bottom: 10px;
    border-bottom: 1px solid rgba(255,0,0,0.5);
    border-top: 1px solid rgba(255,0,0,0.5);
}
</style>
</head>
<body>
<?php
require_once("config/app_webview_config.php");
require_once("app-component.php");
//http://www.jajahome.com/furniture/item_price.php?str=eyJpdGVtX2lkIjoyNTU5LCJ0eXBlIjoyLCJ1c2VyX2lkIjoyMDA5LCJzZXNzaW9uIjp7InNpZCI6IjM3NjcwMiIsInRva2VuIjoiOWMwOGE3Y2VlYWNmMzY3YjMwYTQ3MjA4YjhiZDkyYTA3NTE0MWMifX0=
$str=$_GET["str"];
$get_info=base64_decode($str);
$get_info=json_decode($get_info);
$type=$get_info->type;
$item_id=$get_info->item_id;
$user_id=$get_info->user_id;
$user_sid=$get_info->session->sid;
$user_token=$get_info->session->token;
$user_info=getUserType($user_id);
$user_type = $user_info['user_type'];
//獲取user_type_class
$user_type_class=$user_info['user_type_class']; 

$discount_arr = getUserDiscount($user_type, $user_type_class);
$user_discount = isset($discount_arr[SALES_TYPE_ITEM]['discount'])?$discount_arr[SALES_TYPE_ITEM]['discount']:1;
$item=new Item($item_id);
$fields=json_encode($item->fields,JSON_UNESCAPED_UNICODE);
$price=json_encode($item->getPriceTable(),JSON_UNESCAPED_UNICODE);
$previewTable=json_encode($item->previewTable);
$sql="SELECT brand_id FROM sys_item WHERE id=".$item_id."";
$arr=mysqli_fetch_array(mysqli_query($conn,$sql));

echo	"<script type='text/javascript'>
			var item_id='".$item_id."';
			var submit_type='".($type?$type:2)."';
			var user_id='".$user_id."';
			var user_token='".$user_token."';
			var user_sid='".$user_sid."';
			var item_price_base=".$item->price_base.";
			var item_price_discount=parseFloat(".$item->price_discount.");
			var fields=JSON.parse('".$fields."');
			var price=JSON.parse('".$price."');
			var preview=JSON.parse('".$previewTable."');
			var brand_id='".$arr['brand_id']."';
            var isVip = ".($user_type <= 5 && $user_type >= 3? 'true':'false').";
            var user_discount = parseFloat('".$user_discount."');
		</script>";
?>      
<div id="warning" class="warning">请选择规格</div>
<div class="header">
	<div class="preview"><img src="images/photo_bg.png" id="main_img"></div>
    <div class="info">
    	<div id="title"><?= $item->name?></div>
    	<div id="price"></div>
        <div id="selected_opt_name"></div>
    </div>
</div>
<div id="options">
</div>
<div id="count">
	<div id="name">
    	数量
    </div>
    <div id="controls">
    	<div><div id="minus" onClick="changeCount('m')"><div class="c1"></div></div></div>
    	
        <div><div id="input"><input id="c" type="number" min="1" step="1" value="1" onChange="changeCount(this.value)" disabled></div></div>

        <div><div id="plus" onClick="changeCount('a')"><div class="c1"></div><div class="c2"></div></div></div>
    </div>
</div>
<div class="blank">
</div>
<div id="submit">
	<div onClick="submit_price()" class="submit-btn">确定</div>
</div>
<div id="submit_box" style="display: none">
	<form action="order.php" method="post">
		<input name="obj" type="text" value="">
		<input name="user_id" type="text" value="">
		<input name="user_token" type="text" value="">
	</form>
</div>
<script type="text/javascript">
var default_main_img="images/photo_bg.png";
var item_count= 1;
init();
function init()
{
	for(var i in fields)
	{
		fields[i]["name_div"]=document.createElement("div");//选项总称
		fields[i]["name_div"].classList.add("name_div");
		fields[i]["name_div"].textContent=fields[i].name;
		fields[i]["opt_content_div"]=document.createElement("div");//选项容器
		fields[i]["opt_content_div"].classList.add("opt_content_div");
		fields[i]["opt_content_div"].dataset.selected=-1;//选择项的索引
		fields[i]["opt_content_div"].dataset.key=i;//选项总key
		for(var j in fields[i]["objs"])
		{
			fields[i]["objs"][j]["opt_div"]=document.createElement("div");//单选项
			fields[i]["objs"][j]["opt_div"].classList.add("opt_div");
			fields[i]["objs"][j]["opt_div"].dataset.id=fields[i]["objs"][j]["id"];
			fields[i]["objs"][j]["opt_div"].dataset.p=fields[i]["objs"][j]["prime"];
			fields[i]["objs"][j]["opt_div"].addEventListener("click",optClick,false);
			if(fields[i]["objs"][j]["url"]!=null)
			{
				fields[i]["objs"][j]["opt_div"].innerHTML = '<img src="'+ fields[i]["objs"][j]["url"] +'">';
			}
			else
			{
				fields[i]["objs"][j]["opt_div"].innerHTML = '<div>'+fields[i]["objs"][j]["text"]+'</div>';
			}
			fields[i]["opt_content_div"].appendChild(fields[i]["objs"][j]["opt_div"]);
		}
		document.getElementById("options").appendChild(fields[i]["name_div"]);
		document.getElementById("options").appendChild(fields[i]["opt_content_div"]);
	}
	var tp = parseInt(item_price_base);
	if (tp == 0){
		tp = '请询价';
	}
	document.getElementById("price").innerHTML="<span>¥ "+ tp +"</span>";
	autoSelect();
}
function autoSelect()
{
	var i,contents=document.querySelectorAll(".opt_content_div");
	for(i=0;i<contents.length;i++)
	{
		var opts=contents.item(i).querySelectorAll(".opt_div");
		if(opts.length==1)
		{
			optClick.call(opts[0]);
		}
	}
}
function optClick()
{
	if(this.classList.contains("forbid"))
	{
		return;
	}
	var key=this.parentNode.dataset.key;
	for(var i in fields[key]["objs"])
	{
		if(fields[key]["objs"][i]["opt_div"]==this)
		{
			if(fields[key]["opt_content_div"].dataset.selected!=i)
			{
				fields[key]["opt_content_div"].dataset.selected=i;
				fields[key]["objs"][i]["opt_div"].classList.add("selected");
			}
			else
			{
				fields[key]["opt_content_div"].dataset.selected=-1;
				fields[key]["objs"][i]["opt_div"].classList.remove("selected");
			}
		}
		else if(fields[key]["objs"][i]["opt_div"].classList.contains("selected"))
		{
			fields[key]["objs"][i]["opt_div"].classList.remove("selected");
		}
	}
	optUpdate();
}
function optUpdate()
{
	for(var i in fields)
	{
		for(var j in fields[i]["objs"])
		{
			if(fields[i]["objs"][j]["opt_div"].classList.contains("selected"))
			{
				continue;
			}
			else
			{
				var multi=fields[i]["objs"][j]["prime"];
				for(var k in fields)
				{
					if(k==i||fields[k]["opt_content_div"].dataset.selected==-1){continue;}
					else
					{
						multi=multi*fields[k]["objs"][fields[k]["opt_content_div"].dataset.selected]["prime"];
					}
				}
				var t=1;
				for(var l in price)
				{
					if(price[l]["prime"]%multi==0)
					{
						if(fields[i]["objs"][j]["opt_div"].classList.contains("forbid"))
						{
							fields[i]["objs"][j]["opt_div"].classList.remove("forbid");
						}
						t=0;
						break;
					}
				}
				if(t)
				{
					fields[i]["objs"][j]["opt_div"].classList.add("forbid");
				}
			}
		}
	}
	priceUpdate();
	img_tag_Update();
}
function img_tag_Update()
{
	var t=1;
	var index;
	var selected_opt_div=document.getElementById("selected_opt_name");
	selected_opt_div.innerHTML="";
	for(var i in fields)
	{
		if(i=="fab"||i=="mat")
		{
			index=fields[i]["opt_content_div"].dataset.selected;
			if(fields[i]["opt_content_div"].dataset.selected!=-1)
			{
				t=t*fields[i]["objs"][index]["prime"];
				var selected_opt=document.createElement("div");
				selected_opt.classList.add("selected_opt_tag");
				if(i=="fab")
				{
					selected_opt.textContent="面料: "+fields[i]["objs"][index]["text"];
				}
				else if(i=="mat")
				{
					selected_opt.textContent="材质: "+fields[i]["objs"][index]["text"];
				}
				selected_opt_div.appendChild(selected_opt);
			}
		}
	}
	var tt=1;
	var img=document.getElementById("main_img");
	for(var i in preview)
	{
		if(preview[i]["prime"]==t)
		{
			img.src=preview[i]["url"];
			tt=0;
			break;
		}
	}
	if(tt)
	{
		img.src=default_main_img;
	}
}
function priceUpdate()
{
	var price_div=document.getElementById("price");
	var multi=1,index,now_price,old_price;
	for(var i in fields)
	{
		index=fields[i]["opt_content_div"].dataset.selected;
		if(index==-1)
		{
			var tp = parseInt(item_price_base);
			if (tp == 0){
				tp = '请询价';
			}
			price_div.innerHTML="<span>¥ "+ tp +"</span>";
			return;
		}  
		else
		{
			multi=multi*fields[i]["objs"][index]["prime"];
		}
	}
	for(k in price)
	{
		if(price[k]["prime"]%multi==0)
		{
			var price_base = parseInt(item_price_base);
			var price_discount = parseFloat(item_price_discount);
			var price_custom = parseInt(price[k]["price_custom"]);
			var custom_discount = parseFloat(price[k]["price_discount"]);

			var old_price = price_base + price_custom;
			var now_price = 0;
			if (user_discount > 0 && user_discount < 1){
				now_price = ((price_base + price_custom) * user_discount).toFixed(2);
			}else{
				now_price = ((price_base * price_discount + price_custom * custom_discount)).toFixed(2);
			}

			var vipText = '';
			if (isVip){
				vipText = 'VIP';
			}

			//两个折扣都为1则不显示原价
			if(item_price_discount==1 && price[k]["price_discount"]==1 && user_discount>=1 && !isVip) {
				if (parseInt(now_price)) {
					price_div.innerHTML='<span></span><span class="now_price">¥ '+now_price+'</span>';
				}
				else {
					price_div.innerHTML='<span></span><span class="now_price">请询价</span>';
				}
			}
			else {
				if (parseInt(now_price)) {
					price_div.innerHTML='<del>¥ '+old_price+'</del>&nbsp;&nbsp;<span></span><span class="now_price">'+ vipText +'¥ '+now_price+'</span>';
				}
				else {
					price_div.innerHTML='<span></span><span class="now_price">请询价</span>';
				}
			}
			break;
		}
	}
	document.getElementById("warning").style.display="none";
}
function changeCount(value)
{
	if (value < 1) {
		this.value = 1;
	}
	var c=document.getElementById("c");
	if(value=="a")
	{
		if(parseInt(c.value)<1)
		{
			c.value=1;
		}
		c.value=parseInt(c.value)+1;
		item_count=parseInt(c.value);
		//priceUpdate();
	}
	else if(value=="m")
	{
		if(parseInt(c.value)>1)
		{
			c.value=parseInt(c.value)-1;
		}
		else
		{
			c.value=1;
		}
		item_count=parseInt(c.value);
		//priceUpdate()
	}
	else if(!isNaN(value)&&parseInt(c.value)>=1)
	{
		item_count=parseInt(c.value);
		//priceUpdate();
	}
}
function submit_price()
{
	var index;
	var mult=1;
	var count=(item_count>1?item_count:1);
	var price_id;

	for(var i in fields)
	{
		index=fields[i]["opt_content_div"].dataset.selected;
		if(index==-1)
		{
			document.getElementById("warning").style.display="block";
			return;
		}  
		else
		{
			mult=mult*fields[i]["objs"][index]["prime"];
		}
	}
	for(var i in price)
	{
		if(price[i]["prime"]==mult)
		{
			price_id=price[i]["price_id"]?price[i]["price_id"]:0;
			break;
		}
	}
	var sku_id={};
	var nodes=document.querySelectorAll(".selected");
	for (var i = nodes.length - 1; i >= 0; i--) {
		sku_id[nodes[i].parentNode.dataset.key]=nodes[i].dataset.id;
	}

	if (submit_type==1)//提交到购物车
	{
		var order={};
		order['info']={};
		order['info']['count']=1;
		order['info']['cart_type']=0;
		order['items']=[];
		order['items'][0]={};
		order['items'][0]["count"]=count;
		order['items'][0]["item_id"]=item_id;
		order['items'][0]["price_id"]=price_id;
		order['items'][0]["sku_id"]=sku_id;
		
		var fd=new FormData();
		fd.append("q","submitShopingCart");
		fd.append("order",JSON.stringify(order));
		fd.append("type",0);
		fd.append("user_id",user_id);
		fd.append("user_token",user_token);
		var xhr = new XMLHttpRequest();
		xhr.open("post","calc.php", true);
		xhr.onreadystatechange=function(){
			var html;
		   if(xhr.readyState === 4&&xhr.status === 200)
		   {
			   if(parseInt(xhr.responseText))
			   {
			   		html="<div class=\"result\"><div><img src=\"images/success.png\"></div><div>提交成功</div></div>";
				   	setTimeout('location.href="webView://close"',1500);
			   }
			   else
			   {
				   html="<div class='result'><div><img src='images/failed.png'></div><div>提交失败<br>重新选择</div></div>";
				   setTimeout('history.back()',1500);
			   }
			   document.body.innerHTML=html;
		   }
		};
	}
	else if(submit_type==2)//提交到订单
	{
		var post_order={};
		post_order['singleItem']=[];
		post_order['singleItem'][0]={};
		post_order['singleItem'][0]['info']={};
		post_order['singleItem'][0]['info']['cart_type']=0;
		post_order['singleItem'][0]['items']=[];
		post_order['singleItem'][0]['items'][0]={};
		post_order['singleItem'][0]['items'][0]["count"]=count;
		post_order['singleItem'][0]['items'][0]["item_id"]=item_id;
		post_order['singleItem'][0]['items'][0]["price_id"]=price_id;
		post_order['singleItem'][0]['items'][0]["sku_id"]=sku_id;
		post_order['singleItem'][0]['items'][0]["brand_id"]=brand_id;
		// var form=document.createElement("form");
		// form.action="order.php";
		// form.method="post";

		// var obj=document.createElement("textarea");
		// obj.name="obj";
		// obj.textContent=JSON.stringify(post_order);

		// var userid=document.createElement("input");
		// userid.name="user_id";
		// userid.value=user_id;

		// usertoken=document.createElement("textarea");
		// usertoken.name="user_token";
		// usertoken.textContent=user_token;

		// form.appendChild(obj);
		// form.appendChild(userid);
		// form.appendChild(usertoken);
		// form.submit();
		document.querySelector('#submit_box input[name="obj"]').value=JSON.stringify(post_order);
		document.querySelector('#submit_box input[name="user_id"]').value=<?= $user_id?>;
		document.querySelector('#submit_box input[name="user_token"]').value=<?= "'".$user_token."'"?>;
		document.querySelector('#submit_box>form').submit();
	}
	
	xhr.send(fd);
}
</script>
</body>
</html>
 